#include "Widget.h"
#include "UIRender.h"
#include "Theme.h"
void Widget::Create(Window* window, vec2 pos, vec2 size, UINT32 id)
{
	Control::Create(window, pos, size, id);
}

tstring Widget::GetClassName()
{
	return _T("Widget");
}

bool Widget::OnInit()
{
	Control::OnInit();
	return true;
}

void Widget::OnDestroy()
{
	Control::OnDestroy();
}

void Widget::OnDraw()
{
	Control::OnDraw();

	for (auto& p : paras)
	{
		DrawItem(p.second);
	}
}
void Widget::DrawItem(const Para<double>& item)
{
	int itemh = size.y.val / paras.size();
	int posy = pos.y.val + item.idx * itemh;
	Theme::ITheme* theme = Theme::CustomTheme::GetInstance();
	UIRender::DrawFillRect(pos.x.val, posy, size.x.val, itemh, theme->GetBackColor());

	double percent = (item.v - item.min) / (item.max - item.min);
	int itemw = size.x.val * percent;
	UIRender::DrawFillRect(pos.x.val, posy, itemw, itemh, theme->GetForeColor());
	UIRender::DrawEdgeRect(pos.x.val, posy, size.x.val, itemh, theme->GetBorderColor());
	UIRender::DrawString(glm::vec2(pos.x.val, posy), std::to_wstring(item.v));
}

void Widget::Resize(int w, int h)
{
	Control::Resize(w, h);
}
bool Widget::SetAttribute(const char* attrName, const char* attrVal)
{
	Control::SetAttribute(attrName, attrVal);
	return true;
}
void Widget::ParseXmlElement(TiXmlElement* ele)
{
	TiXmlElement* child = ele->FirstChildElement();
	while (child != NULL)
	{
		ParseAttribute(child);
		child = child->NextSiblingElement();
	}

}
void Widget::ParseAttribute(TiXmlElement* ele)
{
	if (strcmp("Para", ele->Value()) == 0)
	{
		TiXmlAttribute* attr = ele->FirstAttribute();
		Para<double> p;
		std::string _name;
		while (attr)
		{
			if (strcmp(attr->Name(), "name") == 0)
			{
				this->name = attr->Value();
				_name = attr->Value();
			}
			if (strcmp(attr->Name(), "max") == 0)
			{
				p.max = atof(attr->Value());
			}
			if (strcmp(attr->Name(), "min") == 0)
			{
				p.min = atof(attr->Value());
			}
			if (strcmp(attr->Name(), "value") == 0)
			{
				p.v = atof(attr->Value());
			}
			attr = attr->Next();
		}
		p.idx = idx++;
		paras[_name] = p;
	}
}